﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace 通知线程管理器
{
    public partial class 轮询线程管理器 : Form
    {
        PollableThreadManager f = null;
        public 轮询线程管理器()
        {
            InitializeComponent();
            f = new PollableThreadManager();
            f.BeginExection();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            switch (f.WaitForCompleted(1000))
            {
                case AsyncReturn.unknow:
                    MessageBox.Show("unknow");
                    break;
                case AsyncReturn.running:
                    MessageBox.Show("running");
                    break;
                case AsyncReturn.completeUnSuccessfully:
                    MessageBox.Show("completeUnSuccessfully");
                    break;
                case AsyncReturn.completeSuccessfully:
                    MessageBox.Show("completeSuccessfully");
                    break;
                default:
                    break;
            }
        }
    }


    public class PollableThreadManager
    {
        Thread th = null;
        bool mbErr = false;
        public void BeginExection()
        {
            ThreadStart threadStart = new ThreadStart(DoShushu);
            th = new Thread(threadStart);
            th.Start();
        }

        public AsyncReturn WaitForCompleted(int waittime)
        {
            if ((th.ThreadState & (ThreadState.Stopped | ThreadState.Unstarted)) == 0)
            {
                if (!th.Join(waittime))
                {
                    return AsyncReturn.running;
                }
            }

            if (mbErr)
                return AsyncReturn.completeUnSuccessfully;
            return AsyncReturn.completeSuccessfully;
        }

        private void DoShushu()
        {
            try
            {
                int i = 0;
                while (i < 15)
                {

                    Thread.Sleep(1000);
                    i++;
                }
            }
            catch 
            {
                mbErr = true;
            }
        }
    }

    public enum AsyncReturn : int
    {
        unknow = -2,
        running = -1,
        completeUnSuccessfully = 0,
        completeSuccessfully = 1
    }
}